package com.ruoyi.merchant.shopverification.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.merchant.shopverification.config.EnterpriseVerificationConfig;
import com.ruoyi.merchant.shopverification.domain.EnterpriseVerificationRequest;
import com.ruoyi.merchant.shopverification.domain.EnterpriseVerificationResponse;
import com.ruoyi.merchant.shopverification.service.IEnterpriseVerificationService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 企业认证服务实现类
 * 
 * @author zzr
 * @date 2025-09-14
 */
@Service
public class EnterpriseVerificationServiceImpl implements IEnterpriseVerificationService {
    
    private static final Logger logger = LoggerFactory.getLogger(EnterpriseVerificationServiceImpl.class);
    
    @Autowired
    private EnterpriseVerificationConfig config;
    
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public EnterpriseVerificationResponse verifyEnterprise(EnterpriseVerificationRequest request) {
        logger.info("开始企业认证，请求参数：{}", request);
        
        if (request == null || request.getCreditNo() == null || request.getLegalPerson() == null) {
            logger.error("企业认证参数不完整");
            return createErrorResponse("参数不完整，统一社会信用代码和法定代表人姓名为必填项");
        }
        
        try {
            // 构建HTTP请求
            String url = config.getHost() + config.getPath();
            HttpPost httpPost = new HttpPost(url);
            
            // 设置请求头
            httpPost.setHeader("Authorization", "APPCODE " + config.getAppcode());
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            
            // 设置超时配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(config.getConnectTimeout())
                    .setSocketTimeout(config.getTimeout())
                    .build();
            httpPost.setConfig(requestConfig);
            
            // 构建请求参数
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("creditNo", request.getCreditNo()));
            params.add(new BasicNameValuePair("legalPerson", request.getLegalPerson()));
            if (request.getCompanyName() != null && !request.getCompanyName().trim().isEmpty()) {
                params.add(new BasicNameValuePair("companyName", request.getCompanyName()));
            }
            
            // 设置请求体
            httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
            
            // 发送请求
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpResponse response = httpClient.execute(httpPost);
                HttpEntity entity = response.getEntity();
                
                if (entity != null) {
                    String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                    logger.info("企业认证API响应：{}", responseBody);
                    
                    // 解析响应
                    return parseResponse(responseBody);
                } else {
                    logger.error("企业认证API响应为空");
                    return createErrorResponse("API响应为空");
                }
            }
            
        } catch (IOException e) {
            logger.error("调用企业认证API异常", e);
            return createErrorResponse("调用认证服务异常：" + e.getMessage());
        } catch (Exception e) {
            logger.error("企业认证处理异常", e);
            return createErrorResponse("认证处理异常：" + e.getMessage());
        }
    }

    @Override
    public boolean verifyEnterpriseInfo(String creditNo, String legalPerson, String companyName) {
        logger.info("验证企业信息，统一社会信用代码：{}，法定代表人：{}，企业名称：{}", 
                   creditNo, legalPerson, companyName);
        
        // 构建认证请求
        EnterpriseVerificationRequest request = new EnterpriseVerificationRequest();
        request.setCreditNo(creditNo);
        request.setLegalPerson(legalPerson);
        request.setCompanyName(companyName);
        
        // 调用认证接口
        EnterpriseVerificationResponse response = verifyEnterprise(request);
        
        // 判断认证结果
        if (response != null && response.getSuccess() != null && response.getSuccess()) {
            EnterpriseVerificationResponse.VerificationData data = response.getData();
            
            if (data != null) {
                // 检查所有验证项是否都通过
                boolean isVerified = Boolean.TRUE.equals(data.getCreditNo()) && 
                                   Boolean.TRUE.equals(data.getCompanyName()) && 
                                   Boolean.TRUE.equals(data.getLegalPerson());
                
                if (isVerified) {
                    logger.info("企业信息验证通过，统一社会信用代码：{}，企业名称：{}，法定代表人：{}", 
                               data.getCreditNo(), data.getCompanyName(), data.getLegalPerson());
                    return true;
                } else {
                    logger.warn("企业信息验证失败，统一社会信用代码：{}，企业名称：{}，法定代表人：{}", 
                               data.getCreditNo(), data.getCompanyName(), data.getLegalPerson());
                    return false;
                }
            } else {
                logger.error("企业认证响应数据为空：{}", response);
                return false;
            }
        } else {
            logger.error("企业认证响应异常或失败：{}", response);
            return false;
        }
    }
    
    /**
     * 解析API响应
     */
    private EnterpriseVerificationResponse parseResponse(String responseBody) {
        try {
            // 尝试解析JSON响应
            return objectMapper.readValue(responseBody, EnterpriseVerificationResponse.class);
        } catch (Exception e) {
            logger.error("解析API响应失败，响应内容：{}", responseBody, e);
            
            // 如果解析失败，创建错误响应
            EnterpriseVerificationResponse errorResponse = new EnterpriseVerificationResponse();
            errorResponse.setCode(500);
            errorResponse.setMsg("响应解析失败");
            errorResponse.setSuccess(false);
            return errorResponse;
        }
    }
    
    /**
     * 创建错误响应
     */
    private EnterpriseVerificationResponse createErrorResponse(String message) {
        EnterpriseVerificationResponse response = new EnterpriseVerificationResponse();
        response.setCode(500);
        response.setMsg(message);
        response.setSuccess(false);
        return response;
    }
}
